package com.qtzw.filter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String path = request.getContextPath();
        if (path == null || !path.startsWith("/manager")) {
            return false;
        }
        //得到session
        HttpSession session = request.getSession(true);
        // 得到对象
        Object admin = session.getAttribute("admin");
        //判断对象是否存在
        if (admin != null) {
            return true;
        } else {
            // 不存在则跳转到登录页
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
